package top.hepingan.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.CaseImage;
import top.hepingan.java.entity.Cases;
import top.hepingan.java.mapper.CaseImageMapper;
import top.hepingan.java.mapper.CaseMapper;
import top.hepingan.java.utils.BeanUtils;
import top.hepingan.java.vo.CaseVo;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/case")
@RestController
@Slf4j
@RequiredArgsConstructor
public class CaseController {

    private final CaseMapper caseMapper;
    private final CaseImageMapper caseImageMapper;

    /**
     * 获取案例列表
     * @param pageNum
     * @return
     */
    @GetMapping("/list")
    public Result list(@RequestParam Integer pageNum) {
        Page<Cases> page = new Page<>(pageNum, 10);
        Page<Cases> casesPage = caseMapper.selectPage(page, new QueryWrapper<Cases>().lambda()
                .eq(Cases::getStatus, "online")
                .orderByDesc(Cases::getCreatedTime));
        List<CaseVo> caseVos = new ArrayList<>();
        casesPage.getRecords().forEach(cases -> {
            List<CaseImage> caseImages = caseImageMapper.selectList(new QueryWrapper<CaseImage>().lambda()
                    .eq(CaseImage::getCaseId, cases.getId()));
            List<String> imageList = new ArrayList<>();
            caseImages.forEach(caseImage -> imageList.add(caseImage.getImgUrl()));
            caseVos.add(BeanUtils.copyClassProperTies(cases, CaseVo.class)
                    .setImageList(imageList));
        });
        return Result.data(caseVos);
    }


    @GetMapping("/detail")
    public Result detail(@RequestParam Long id) {
        Cases cases = caseMapper.selectById(id);
        List<CaseImage> caseImages = caseImageMapper.selectList(new QueryWrapper<CaseImage>().lambda()
                .eq(CaseImage::getCaseId, id));
        List<String> imageList = new ArrayList<>();
        caseImages.forEach(caseImage -> imageList.add(caseImage.getImgUrl()));
        return Result.data(BeanUtils.copyClassProperTies(cases, CaseVo.class).setImageList(imageList));
    }

}
